package com.carsa.blackberry.ui.screen.gruposentregas;

import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.carsa.blackberry.CarsaApp;
import com.carsa.blackberry.MainKeys;
import com.carsa.blackberry.domain.dto.ArticuloDTO;
import com.carsa.blackberry.domain.dto.EntregaDTO;
import com.carsa.blackberry.domain.dto.ReasonDTO;
import com.carsa.blackberry.domain.dto.SecondReasonDTO;
import com.carsa.blackberry.domain.services.impl.EntregasServiceImpl;
import com.carsa.blackberry.ui.UIKeys;
import com.carsa.blackberry.ui.screen.common.BasicScreen;
import com.carsa.blackberry.util.Util;
import com.carsa.blackberry.util.ui.UIUtil;
import com.carsa.blackberry.util.ui.widget.GridFieldManager;

/**
 * @author Nahuel Barrios.
 * @since 22/07/2010.
 * @version 1.0
 */
public class SeleccionarMotivoFallidaParcialScreen extends BasicScreen {

    private EntregaDTO _unaEntrega;
    private Hashtable  _reasons = new Hashtable();

    private Hashtable  _pairs   = new Hashtable();

    public SeleccionarMotivoFallidaParcialScreen(EntregaDTO unaEntrega) {
	super(UIKeys.TITLE_ARTICULOS);
	super.customizeScreen();

	this._unaEntrega = unaEntrega;

	super._bf_accept = new ButtonField(UIKeys.TITLE_ACCEPT, FIELD_LEFT);
	super._bf_accept.setChangeListener(new FieldChangeListener() {
	    public void fieldChanged(Field field, int context) {
		if (Util.getBooleanConditionFrom(Dialog.ask(Dialog.D_YES_NO, UIKeys.POPUP_CONFIRMAR_OPERACION))) {
		    performSeleccionarMotivos();
		    UiApplication.getUiApplication().popScreen(_currentScreen);
		}
	    }
	});

	GridFieldManager grid_bottomToolbar = new GridFieldManager(2, 0);
	grid_bottomToolbar.add(_bf_accept);
	super.addBackButton(grid_bottomToolbar);

	// ---------------------------------------------------
	// Con todos los controles ya seteados, armo la vista.
	_mainManager.add(com.carsa.blackberry.util.ui.UIUtil.getEmptyLine());
	_mainManager.add(this.makeGridWith(_unaEntrega.getArticles()));

	com.carsa.blackberry.util.ui.UIUtil.addNewEmptyLine(_mainManager, 2);
	_mainManager.add(grid_bottomToolbar);
	this.add(_mainManager);
    }

    /**
     * Arma el listado de articulos, con los motivos y la descripcion se los articulos.
     * 
     * @return
     */
    private VerticalFieldManager makeGridWith(Vector parameters) {
	// El VerticalFieldManager donde voy a ir agregando cada fila.
	VerticalFieldManager vManager = new VerticalFieldManager();

	// Como los headers llevan una letra distinta, los cargo de manera distinta.
	GridFieldManager grid_headers = new GridFieldManager(2, 0);

	Vector headers = new Vector();
	headers.addElement(UIKeys.TITLE_ARTICULOS);
	headers.addElement(UIKeys.TITLE_MOTIVO);
	grid_headers = UIUtil.loadHeadersToGrid(grid_headers, UIUtil.prepareHeadersForGrid(headers, this));

	vManager.add(grid_headers);

	// Recupero los motivos de entrega fallida.
	Hashtable reasons = (Hashtable) CarsaApp.getMemory().get(MainKeys.PARAMETER_REASONS_AND_SUBREASONS);
	// Seteo el submotivo con valores de codigos "" para cuando el articulo ese fue exitoso.
	Vector reasonsVector = new Vector();
	SecondReasonDTO noReason = new SecondReasonDTO("Ninguno", "", "X", "");
	reasonsVector.addElement(noReason.getDescript());
	_pairs.put(noReason.getDescript(), noReason);

	Enumeration elements = reasons.elements();
	for (int idx = 0; elements.hasMoreElements(); idx++) {
	    ReasonDTO aReason = (ReasonDTO) elements.nextElement();

	    Vector subreasons = aReason.getSubreasons();
	    Enumeration subElements = subreasons.elements();
	    while (subElements.hasMoreElements()) {
		SecondReasonDTO secondReason = (SecondReasonDTO) subElements.nextElement();
		if (secondReason.isFlepaSetted()) {
		    reasonsVector.addElement(secondReason.getDescript());
		    _pairs.put(secondReason.getDescript(), secondReason);
		}
	    }
	}
	Object[] reasonsArray = new Object[reasonsVector.size()];
	reasonsVector.copyInto(reasonsArray);

	// Ahora empiezo a iterar los articulos y a agregarlos al listado.
	Enumeration articles = parameters.elements();
	for (int idx=0; articles.hasMoreElements(); idx++) {
	    final ArticuloDTO anArticle = (ArticuloDTO) articles.nextElement();
	    final int idxForArticle= idx;

	    GridFieldManager grid_aRow = new GridFieldManager(new int[] { 140, 180 }, 0);

	    grid_aRow.add(new LabelField(Util.trimLeft(anArticle.getMatnr())));
	    final ObjectChoiceField combo_reason = new ObjectChoiceField("", reasonsArray, 0, FIELD_LEFT);
	    combo_reason.setChangeListener(new FieldChangeListener() {
		public void fieldChanged(Field field, int context) {
		    String selectedValue = (String) combo_reason.getChoice(combo_reason.getSelectedIndex());
		    
		    _reasons.put(new Integer(idxForArticle), _pairs.get(selectedValue));
		}
	    });
	    _reasons.put(new Integer(idxForArticle), noReason);// De entrada, todos los articulos tienen el motivo "Ninguno"
	    grid_aRow.add(combo_reason);

	    vManager.add(com.carsa.blackberry.util.ui.UIUtil.getEmptyLine());
	    vManager.add(grid_aRow);
	    vManager.add(new LabelField(anArticle.getArktx()));
	    vManager.add(com.carsa.blackberry.util.ui.UIUtil.getEmptyLine());
	    vManager.add(new SeparatorField());
	    
	}

	return vManager;
    }

    /**
     * Realiza todas las acciones vinculadas a la confirmacion del usuario de calificar la entrega como fallida.
     */
    public void performSeleccionarMotivos() {
	Hashtable parameters = new Hashtable();

	parameters.put(MainKeys.PARAMETER_DATE_TIME_MOMENT, Calendar.getInstance().getTime());

	parameters.put(MainKeys.PARAMETER_ARTICLES_REASONS, _reasons);

	new EntregasServiceImpl().markPartialFailEntregaAs(_unaEntrega, parameters);

//	UiApplication.getUiApplication().popScreen(this);// TODO : Functionality : si descomento esto, tira Exception!
	UiApplication.getUiApplication().pushScreen(new GruposEntregasScreen(true));
    }

    /**
     * Sobreescribo la funcionalidad por default que puse en BasicScreen para cada pantalla que tenga el boton "volver".
     * Hago esto, en este metodo porque el boton "volver" lo que hace cuando es presionado es llamar a este metodo.
     */
    public boolean onClose() {
	UiApplication.getUiApplication().popScreen(this);
	return false;
    }

}
